package host.skiree.nettydemo.netty.introduction.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author gcl
 * @date 2022/9/8 15:07
 */
@Slf4j
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        // 带有Future Promise 的类型都是和异步方法配合使用的，用来处理结果的
        EventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // connect连接到服务器 异步非阻塞 主线程发起了调用 真正执行连接的是NIO线程
                .connect(new InetSocketAddress("127.0.0.1", 8080));
        channelFuture.sync(); // 阻塞当前线程，直到NIO线程连接建立完成
        Channel channel = channelFuture.channel();
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String str = scanner.next();
                if (str.equals("q")){
                    try {
                        channel.close().sync();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        log.error("处理关闭后的操作");
                    }
                    break;
                }
                channel.writeAndFlush(str);
            }

        }).start();

        // 获取 ClosedFuture 对象 1 同步处理关闭
        // 1 同步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        log.error("waiting close...");
        closeFuture.sync();
        log.error("同步...处理以后的业务");
        // 2 异步处理关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.error("异步...处理以后的业务");
            }
        });

        // 上边的代码是关闭了 Channel 但是 时间循环组还没有被释放 通过执行下边的代码结果
        group.shutdownGracefully().sync();


    }

}
